package com.gombe.credit.app.ui.activity

import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.gombe.credit.app.GombeCreditApp
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.databinding.ActGombeCreditCameraOcrBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.request.HttpHelper
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.GombeCreditImageLoader
import com.gombe.credit.app.utils.imgcovert.ImageConvert
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/22 11:15
 * @Annotation：身份证、驾驶证、护照拍照
 */
class ActGombeCreditCameraOcr: CommonActivity() {
    lateinit var binding: ActGombeCreditCameraOcrBinding

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUsePath = ""

    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditCameraOcrBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, false)
        binding.ocrTitleLayout.setPadding(0, GombeCreditTitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCameraOcr()
    }

    override fun initGombeCreditListener() {
        binding.ocrImgBack.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                finish()
            }
        })

        binding.ocrImgCustomer.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                val eventTitle = "OcrCamera Page"
                showCustomerDialog(eventTitle)
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,eventTitle)
            }
        })

        //拍照
        binding.imgOcrTake.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CAMERA_TAKE_PHOTO,"OcrCamera Page")
                takeCameraOcrFilePhoto()
            }
        })

        //重拍
        binding.imgOcrRemake.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_OCR_UPLOAD_RETAKE,"OcrCamera Page")
                showCameraOcrTakeView()
            }
        })

        //使用
        binding.imgOcrUse.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_OCR_UPLOAD_USE_PHOTO,"OcrCamera Page")
                uploadGombeCreditImageAction(imgUsePath)
            }
        })
    }

    override fun takeGombeCreditData() {
    }

    /**
     * 打开相机预览
     */
    private fun startCameraOcr() {
        showCameraOcrTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.ocrCameraView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开后置摄像头
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeCameraOcrFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = GombeCreditApp.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata()
            metadata.isReversedHorizontal = true
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val imgUri = outputFileResults.savedUri

                    GombeCreditLogger.e("take photo complete>>>>>>>${imgUri?.path}")
                    // 图片处理
                    ImageConvert.covert(context = this@ActGombeCreditCameraOcr, uri = imgUri) { localPath, bitmap ->
                        if (localPath != null){
                            imgUsePath = localPath
                            GombeCreditLogger.e("imageConvert success>>>>>>>$localPath")
                            GombeCreditImageLoader.instance?.loadImageUrl(this@ActGombeCreditCameraOcr,binding.ocrPreview,localPath)
                            showCameraOcrCompleteView()
                        }
                    }
                }
                override fun onError(exception: ImageCaptureException) {
                    GombeCreditLogger.e("take photo failed>>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showCameraOcrTakeView(){
        binding.ocrMaskView.setMaskColor(getColor(R.color.gombe_credit_80000000))
        binding.ocrPreview.visibility = View.GONE
        binding.imgOcrTake.visibility = View.VISIBLE
        binding.imgOcrUse.visibility = View.GONE
        binding.imgOcrRemake.visibility = View.GONE
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCameraOcrCompleteView(){
        binding.ocrMaskView.setMaskColor(getColor(R.color.black))
        binding.ocrPreview.visibility = View.VISIBLE
        binding.imgOcrTake.visibility = View.GONE
        binding.imgOcrUse.visibility = View.VISIBLE
        binding.imgOcrRemake.visibility = View.VISIBLE
    }

    /**
     * 图片上传完成
     */
    fun showGombeCreditOcrUploadImageSuccess(imgPath: String, imgUrl: String) {
        hideGombeCreditLoading()
        val intent = intent
        intent.putExtra("imgLocalPath",imgPath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    /**
     * 图片上传
     */
    private fun uploadGombeCreditImageAction(imgPath: String){
        showGombeCreditLoading(isTOuchOut = false, isCancel = false)
        HttpHelper.setTag(this)
        HttpHelper.upload(imgPath,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    val imgUrl = it.optString("url")
                    showGombeCreditOcrUploadImageSuccess(imgPath,imgUrl)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showGombeCreditToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_OCR_CAMERA_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.cancelTag(this)
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_OCR_CAMERA_END)
        cameraExecutor.shutdown()
    }
}